-- NewEquipRender 对Res.NewEquipNode的解析 适用所有装备显示

local ClassRef = app.mvc.createRenderClass(...)
local Armature = require("app.public.avatar.Armature")
local jewelNum = 4
local crystalNum = 6
local SLOT_GAP = 12

local gemDistanceOfX = 0 -- 宝石孔X间距
local gemMiddlePosX = 0 -- 宝石孔居中X坐标

local crystalDistanceOfX = 0 -- 水晶孔X间距
local crystalMiddlePosX = 0 -- 水晶孔居中X坐标
local table_insert = table.insert

function ClassRef.create(node)
	local rootNode = node or cc.CSLoader:createNode(Res.NewEquipNode)

	--兼容 node 分层不支持
	local panel = rootNode:getChildByName('Panel')
	if panel then
		local parent = rootNode:getParent()
		panel:setPosition(rootNode:getPosition())
		panel:setScaleX(rootNode:getScaleX())
		panel:setScaleY(rootNode:getScaleY())
		local action = rootNode:getTimeline()
		local newAction 
		if action then
			newAction = action:clone()
			panel:runAction(newAction)
			newAction:gotoFrameAndPlay(0, true)
		end
		if parent then
			panel:retain()
			panel:removeFromParent(false)
			rootNode:removeFromParent()
			parent:addChild(panel)
			panel:release()
		end
		rootNode = panel
	end
	local sprite = ClassRef.extend(rootNode)

	if node == nil then
		ccui.Helper:doLayout(sprite)
	end
	sprite:init()
	return sprite
end


function ClassRef:init(data)
	self.super.init(self, data)

	self._equipGridStrengthPanelShown = false -- 装备强化panel是否显示
	self._tipEnable = false
	self._isTouchTip = false

	-- self:setContentSize(self:getContentSize())

	self:setSelected(false)
	self:addTouchEventListener(function(sender, eventType)
		if eventType == ccui.TouchEventType.ended then
			if self._equipGridStrengthPanelShown and not string.find( GD:getSystemStrPar("recastlocation", "nil"), tostring( self._pos ) ) then
				display.pushToast(L("tips_3000332"))
			else
				self:setSelected( true )

				if self._isTouchTip then
					self:setSelected(false)
				else
					executeFunc(self._onClick, self)
				end
			end
		end
	end)

	gemDistanceOfX = self._ui["Panel_gem/gem_2"]:getPositionX() - self._ui["Panel_gem/gem_1"]:getPositionX()
	gemMiddlePosX = self._ui["Panel_gem"]:getContentSize().width/2

	crystalDistanceOfX = self._ui["Panel_wing/gem_2"]:getPositionX() - self._ui["Panel_wing/gem_1"]:getPositionX()
	crystalMiddlePosX = self._ui["Panel_wing"]:getContentSize().width/2

	-- self:refresh()
end

function ClassRef:refresh()
	if self._data then
		self._ui["grade"]:setVisible(true)
		self._ui["icon"]:setVisible(true)
		self._ui["equip_bg"]:setVisible(false)

		self._ui["grade"]:loadTexture(self._data:getIconBg())
		self._ui["icon"]:loadTexture(self._data:getIcon())

		self:showGemSlots(self._data:getAllSlots())
		self:showRockSlots(self._data:getAllCrystalSlots(), self._data:getRockNum())

		self._ui["Panel_lock"]:setVisible( true )

		if string.find( GD:getSystemStrPar("recastlocation", "nil"), tostring( self:getDefPos() ) ) then -- 是可强化部位？
			self._ui["num"]:setVisible( true )
			self:setStrengthenedLv( self._data:getStrengthLv() )
			self:setContinueStrengthen( self._data:canContinueStrength() ) -- 可继续强化
		else
			self._ui["img_ContinueFlag"]:setVisible( false )
			self._ui["num"]:setVisible( false )
		end

		self:setClickEnable( true )
	else
		self._ui["grade"]:setVisible(false)
		self._ui["icon"]:setVisible(false)
		self._ui["Panel_gem"]:setVisible(false)
		self._ui["Panel_wing"]:setVisible(false)
		self._ui["equip_bg"]:setVisible(true)

		self._ui["Panel_lock"]:setVisible( false )

		if string.find( GD:getSystemStrPar("recastlocation", "nil"), tostring( self:getDefPos() ) ) then -- 是可强化部位？
			self._ui["num"]:setVisible( true )
			self:setStrengthenedLv( UD:getEquipGridStrengthByPos( self:getDefPos() ) )
		else
			self._ui["num"]:setVisible( false )
		end
		self:setContinueStrengthen( false )

		self:setClickEnable( false )
	end
end

function ClassRef:showGemSlots(slots)
	self._ui["Panel_gem"]:setVisible(#slots > 0)
	if #slots > 0 then
		local showGems = {}
		local gemVisibleNum = 0 -- 宝石孔可见数量
		for i=1,jewelNum do
			local slot = slots[i]
			local gem = self._ui["Panel_gem/gem_" .. i]
			gem:setVisible(slot ~= nil)
			table_insert(showGems,gem)
			if slot then
				gemVisibleNum = gemVisibleNum + 1
				gem:getChildByName("bg"):loadTexture( GD:getImagePath( Res.slotIconPath, "common_cell_gem1" ) )
				if slot:hasJewel() then
					gem:getChildByName("gem"):setVisible( true )
					gem:getChildByName("gem"):loadTexture( slot.jewel:getMiniIcon() )
				else
					-- gem:getChildByName("bg"):loadTexture( GD:getImagePath( Res.slotIconPath, "common_cell_gem1" ) )
					gem:getChildByName("gem"):setVisible( false )
				end
			end
		end
		-- 以下：做宝石孔的动态位置调整
		display.autoAdjustNodesPosX( self._ui["Panel_gem"]:getContentSize().width, showGems, gemVisibleNum, gemDistanceOfX)
	end
end

function ClassRef:showRockSlots(crystalIds,rockNum)
	self._ui["Panel_wing"]:setVisible(rockNum > 0)
	if rockNum > 0 then
		local gemVisibleNum = rockNum -- 水晶孔可见数量
		local showGems = {}
		for i=1,crystalNum do
			local rockId = crystalIds[i]
			local gem = self._ui["Panel_wing/gem_" .. i]
			table_insert(showGems,gem)
			gem:setVisible(rockNum >= i)
			if rockId then
				local rockInfo = GD:queryRockById(tonumber(rockId))
				if rockInfo then
					gem:getChildByName("wing"):setVisible( true )
					gem:getChildByName("wing"):loadTexture( GD:getImagePath(Res.slotIconPath, "common_cell_crystal"..tostring(rockInfo.type)))
				end
			else
				gem:getChildByName("wing"):setVisible( false )
			end
		end

		display.autoAdjustNodesPosX( self._ui["Panel_wing"]:getContentSize().width, showGems, gemVisibleNum, crystalDistanceOfX)
	end
end

function ClassRef:setDefPos(pos)
	self._pos = pos
	self._ui["equip_bg"]:loadTexture(GD:getEquipPosDefIcon(pos))
end

function ClassRef:getDefPos()
	return self._pos
end

function ClassRef:isSelected()
	return self._ui["selected"]:isVisible()
end
function ClassRef:setSelected(b)
	self._ui["selected"]:setVisible( b )
end
function ClassRef:setClickEnable(b)
	self:setTouchEnabled(b)
end

-- 是否可继续强化
function ClassRef:setContinueStrengthen(b)
	self._ui["img_ContinueFlag"]:setVisible(b)
end

-- 已强化等级
function ClassRef:setStrengthenedLv( num )
	if num then
		self._ui["num"]:setString( "+" .. num )
	else
		self._ui["num"]:setString( "+0" )
	end
end

--pos = {x=, y=}
function ClassRef:setTipEnable(b, pos, isTouch)
	self._tipEnable = b
	self._tipPos = pos
	self._isTouchTip = isTouch or false
	self:addTouchEvent()
end

function ClassRef:addTouchEvent()
	if self._isTouchTip then
		local function touchEvent(sender, eventType)
			if not self._isTouchTip then return end
			if eventType == ccui.TouchEventType.began then
				self._delayAct = sender:performWithDelay(function()
						self._delayAct = nil

						local worldPos = self:convertToWorldSpace(cc.p(0,0))
						self._tipPos = self._tipPos or {x=2/5, y=1/2}
						if worldPos.x < display.cx then
							self._tipPos.x = 5/8
						else
							self._tipPos.x = 1/5
						end
						self:showTip()
					end, 0.1)

				self:setSelected(true)
			elseif eventType == ccui.TouchEventType.canceled or eventType == ccui.TouchEventType.ended then
				if self._delayAct then
					sender:stopAction(self._delayAct)
					self._delayAct = nil
					if eventType == ccui.TouchEventType.ended then
						executeFunc(self._onClick, self)
					end
				else
					UIHandler:hideFloatPanel()
				end
				if eventType == ccui.TouchEventType.canceled then
					self:setSelected(false)
				end
			end
		end
		self:addTouchEventListener(touchEvent)
	end
end

function ClassRef:showTip()
	if self._tipEnable and self._data then
		local data = self._data

		local param = {itemId=tonumber(data.tid)}
		param.dataTemp = data
		param.tipsType = Enums.TipsType.equip
		param.closeCallBack = function()
			if not tolua.isnull(self) then
				self:setSelected(false)
			end
		end
		local boundingBoxTemp = self:getBoundingBox()
		local worldPosTemp = self:getParent():convertToWorldSpace( cc.p( boundingBoxTemp.x, boundingBoxTemp.y ) )
		boundingBoxTemp.x = worldPosTemp.x
		boundingBoxTemp.y = worldPosTemp.y
		param.boundingBox = boundingBoxTemp
		app:dispatchCustomEvent("EVENT_OPEN_FLOAT", {params=param})
	end
end

function ClassRef:setClickHandler(func)
	self._onClick = func
end

function ClassRef:setEquipGridStrengthPanelVisble( flag )
	self._equipGridStrengthPanelShown = flag
end

function ClassRef:playStrengthSuccessAmi()
	if not self._successArmature then
		local params = {
			armatureName = "QH1",
			path = Res.EquipStrengthSuccessAmi
		}
		local armature = Armature.create(params)
		armature:setPosition(0, 21.5)
		self._ui["num"]:addChild(armature)
		self._successArmature = armature
	end
	self._successArmature:play("QH1", 1)
end

return ClassRef
